import math
import cv2
import numpy as np
import random
import os
import logging
import multiprocessing
from PIL import Image
class WarpMLS:
    def __init__(self, src, src_pts, dst_pts, dst_w, dst_h, trans_ratio=1.):
        self.src = src
        self.src_pts = src_pts
        self.dst_pts = dst_pts
        self.pt_count = len(self.dst_pts)
        self.dst_w = dst_w
        self.dst_h = dst_h
        self.trans_ratio = trans_ratio
        self.grid_size = 100
        self.rdx = np.zeros((self.dst_h, self.dst_w))
        self.rdy = np.zeros((self.dst_h, self.dst_w))

    @staticmethod
    def __bilinear_interp(x, y, v11, v12, v21, v22):
        return (v11 * (1 - y) + v12 * y) * (1 - x) + (v21 *
                                                      (1 - y) + v22 * y) * x

    def generate(self):
        self.calc_delta()
        return self.gen_img()

    def calc_delta(self):
        w = np.zeros(self.pt_count, dtype=np.float32)

        if self.pt_count < 2:
            return

        i = 0
        while 1:
            if self.dst_w <= i < self.dst_w + self.grid_size - 1:
                i = self.dst_w - 1
            elif i >= self.dst_w:
                break

            j = 0
            while 1:
                if self.dst_h <= j < self.dst_h + self.grid_size - 1:
                    j = self.dst_h - 1
                elif j >= self.dst_h:
                    break

                sw = 0
                swp = np.zeros(2, dtype=np.float32)
                swq = np.zeros(2, dtype=np.float32)
                new_pt = np.zeros(2, dtype=np.float32)
                cur_pt = np.array([i, j], dtype=np.float32)

                k = 0
                for k in range(self.pt_count):
                    if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:
                        break

                    w[k] = 1. / (
                        (i - self.dst_pts[k][0]) * (i - self.dst_pts[k][0]) +
                        (j - self.dst_pts[k][1]) * (j - self.dst_pts[k][1]))

                    sw += w[k]
                    swp = swp + w[k] * np.array(self.dst_pts[k])
                    swq = swq + w[k] * np.array(self.src_pts[k])

                if k == self.pt_count - 1:
                    pstar = 1 / sw * swp
                    qstar = 1 / sw * swq

                    miu_s = 0
                    for k in range(self.pt_count):
                        if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:
                            continue
                        pt_i = self.dst_pts[k] - pstar
                        miu_s += w[k] * np.sum(pt_i * pt_i)

                    cur_pt -= pstar
                    cur_pt_j = np.array([-cur_pt[1], cur_pt[0]])

                    for k in range(self.pt_count):
                        if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:
                            continue

                        pt_i = self.dst_pts[k] - pstar
                        pt_j = np.array([-pt_i[1], pt_i[0]])

                        tmp_pt = np.zeros(2, dtype=np.float32)
                        tmp_pt[0] = np.sum(pt_i * cur_pt) * self.src_pts[k][0] - \
                                    np.sum(pt_j * cur_pt) * self.src_pts[k][1]
                        tmp_pt[1] = -np.sum(pt_i * cur_pt_j) * self.src_pts[k][0] + \
                                    np.sum(pt_j * cur_pt_j) * self.src_pts[k][1]
                        tmp_pt *= (w[k] / miu_s)
                        new_pt += tmp_pt

                    new_pt += qstar
                else:
                    new_pt = self.src_pts[k]

                self.rdx[j, i] = new_pt[0] - i
                self.rdy[j, i] = new_pt[1] - j

                j += self.grid_size
            i += self.grid_size

    def gen_img(self):
        src_h, src_w = self.src.shape[:2]
        dst = np.zeros_like(self.src, dtype=np.float32)

        for i in np.arange(0, self.dst_h, self.grid_size):
            for j in np.arange(0, self.dst_w, self.grid_size):
                ni = i + self.grid_size
                nj = j + self.grid_size
                w = h = self.grid_size
                if ni >= self.dst_h:
                    ni = self.dst_h - 1
                    h = ni - i + 1
                if nj >= self.dst_w:
                    nj = self.dst_w - 1
                    w = nj - j + 1

                di = np.reshape(np.arange(h), (-1, 1))
                dj = np.reshape(np.arange(w), (1, -1))
                delta_x = self.__bilinear_interp(
                    di / h, dj / w, self.rdx[i, j], self.rdx[i, nj],
                    self.rdx[ni, j], self.rdx[ni, nj])
                delta_y = self.__bilinear_interp(
                    di / h, dj / w, self.rdy[i, j], self.rdy[i, nj],
                    self.rdy[ni, j], self.rdy[ni, nj])
                nx = j + dj + delta_x * self.trans_ratio
                ny = i + di + delta_y * self.trans_ratio
                nx = np.clip(nx, 0, src_w - 1)
                ny = np.clip(ny, 0, src_h - 1)
                nxi = np.array(np.floor(nx), dtype=np.int32)
                nyi = np.array(np.floor(ny), dtype=np.int32)
                nxi1 = np.array(np.ceil(nx), dtype=np.int32)
                nyi1 = np.array(np.ceil(ny), dtype=np.int32)

                if len(self.src.shape) == 3:
                    x = np.tile(np.expand_dims(ny - nyi, axis=-1), (1, 1, 3))
                    y = np.tile(np.expand_dims(nx - nxi, axis=-1), (1, 1, 3))
                else:
                    x = ny - nyi
                    y = nx - nxi
                dst[i:i + h, j:j + w] = self.__bilinear_interp(
                    x, y, self.src[nyi, nxi], self.src[nyi, nxi1],
                    self.src[nyi1, nxi], self.src[nyi1, nxi1])

        dst = np.clip(dst, 0, 255)
        dst = np.array(dst, dtype=np.uint8)

        return dst


def tia_distort(src, segment=4):
    img_h, img_w = src.shape[:2]

    cut = img_w // segment
    thresh = cut // 3

    src_pts = list()
    dst_pts = list()

    src_pts.append([0, 0])
    src_pts.append([img_w, 0])
    src_pts.append([img_w, img_h])
    src_pts.append([0, img_h])

    dst_pts.append([np.random.randint(thresh), np.random.randint(thresh)])
    dst_pts.append(
        [img_w - np.random.randint(thresh), np.random.randint(thresh)])
    dst_pts.append(
        [img_w - np.random.randint(thresh), img_h - np.random.randint(thresh)])
    dst_pts.append(
        [np.random.randint(thresh), img_h - np.random.randint(thresh)])

    half_thresh = thresh * 0.5

    for cut_idx in np.arange(1, segment, 1):
        src_pts.append([cut * cut_idx, 0])
        src_pts.append([cut * cut_idx, img_h])
        dst_pts.append([
            cut * cut_idx + np.random.randint(thresh) - half_thresh,
            np.random.randint(thresh) - half_thresh
        ])
        dst_pts.append([
            cut * cut_idx + np.random.randint(thresh) - half_thresh,
            img_h + np.random.randint(thresh) - half_thresh
        ])

    trans = WarpMLS(src, src_pts, dst_pts, img_w, img_h)
    dst = trans.generate()

    return dst


def tia_stretch(src, segment=4):
    img_h, img_w = src.shape[:2]

    cut = img_w // segment
    thresh = cut * 4 // 5

    src_pts = list()
    dst_pts = list()

    src_pts.append([0, 0])
    src_pts.append([img_w, 0])
    src_pts.append([img_w, img_h])
    src_pts.append([0, img_h])

    dst_pts.append([0, 0])
    dst_pts.append([img_w, 0])
    dst_pts.append([img_w, img_h])
    dst_pts.append([0, img_h])

    half_thresh = thresh * 0.5

    for cut_idx in np.arange(1, segment, 1):
        move = np.random.randint(thresh) - half_thresh
        src_pts.append([cut * cut_idx, 0])
        src_pts.append([cut * cut_idx, img_h])
        dst_pts.append([cut * cut_idx + move, 0])
        dst_pts.append([cut * cut_idx + move, img_h])

    trans = WarpMLS(src, src_pts, dst_pts, img_w, img_h)
    dst = trans.generate()

    return dst


def tia_perspective(src):
    img_h, img_w = src.shape[:2]

    thresh = img_h // 2

    src_pts = list()
    dst_pts = list()

    src_pts.append([0, 0])
    src_pts.append([img_w, 0])
    src_pts.append([img_w, img_h])
    src_pts.append([0, img_h])

    dst_pts.append([0, np.random.randint(thresh)])
    dst_pts.append([img_w, np.random.randint(thresh)])
    dst_pts.append([img_w, img_h - np.random.randint(thresh)])
    dst_pts.append([0, img_h - np.random.randint(thresh)])

    trans = WarpMLS(src, src_pts, dst_pts, img_w, img_h)
    dst = trans.generate()

    return dst


def open_txt(file_name):
    with open(file_name, 'r') as f:
        try:
            line = f.readline()
            while line:
                yield line.strip()
                line = f.readline()
        except:
            print('No value')
def resize_norm_img(img):
    imgH = 32
    h = img.shape[0]
    w = img.shape[1]
    ratio = w / float(h)
    # if math.ceil(imgH * ratio) > imgW:
    #     resized_w = imgW
    # else:
    resized_w = int(math.ceil(imgH * ratio))
    resized_image = cv2.resize(img, (resized_w, imgH))
    # resized_image = resized_image.transpose((2, 0, 1))
    # mean = np.mean(resized_image)
    # resized_image = resized_image.astype('float32')
    # if image_shape[0] == 1:
    #     resized_image = resized_image / 255
    #     resized_image = resized_image[np.newaxis, :]
    # else:
    #     resized_image = resized_image.transpose((2, 0, 1)) / 255
    # resized_image -= 0.5
    # resized_image /= 0.5
    # padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32) + mean
    # padding_im[:, :, 0:resized_w] = resized_image
    # padding_im = padding_im.transpose((1, 2, 0))
    return resized_image
def jitter(img):
    """
    jitter
    """
    w, h, _ = img.shape
    if h > 10 and w > 10:
        thres = min(w, h)
        s = int(random.random() * thres * 0.2)
        src_img = img.copy()
        for i in range(s):
            img[i:, i:, :] = src_img[:w - i, :h - i, :]
        return img
    else:
        return img
def flag():
    """
    flag
    """
    return 1 if random.random() > 0.5000001 else -1
def cvtColor(img):
    """
    cvtColor
    """
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    delta = 0.001 * random.random() * flag()
    hsv[:, :, 2] = hsv[:, :, 2] * (1 + delta)
    new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    return new_img
def blur(img):
    """
    blur
    """
    h, w, _ = img.shape
    if h > 10 and w > 10:
        return cv2.GaussianBlur(img, (5, 5), 1)
    else:
        return img
def add_gasuss_noise(image, mean=0, var=0.1):
    """
    Gasuss noise
    """

    noise = np.random.normal(mean, var**0.5, image.shape)
    out = image + 0.5 * noise
    out = np.clip(out, 0, 255)
    out = np.uint8(out)
    return out
def get_crop(image):
    """
    random crop   Crop后加resize
    """
    h, w, _ = image.shape
    top_min = 0
    top_max = 5
    top_crop = int(random.randint(top_min, top_max))
    top_crop = min(top_crop, h - 1)
    crop_img = image.copy()
    ratio = random.randint(0, 1)
    if ratio:
        crop_img = crop_img[top_crop:h, :, :]   # 上裁剪
    else:
        crop_img = crop_img[0:h - top_crop, :, :]   # 下裁剪
    
    return crop_img



def img_aug(img):
    # if i % 100000 == 0:
    #     print(i)
    # img_path = txt_list[i].split('\t')[0]
    # gt = txt_list[i].split('\t')[1].strip()

    # img = cv2.imread(img_path)
    # img = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)
    # img = np.asarray(img)
    is_jitter = random.randint(0, 1)
    if is_jitter:
        img = jitter(img)
    
    is_blur = random.randint(0, 1)
    if is_blur:
        img = blur(img)
    
    is_noise = random.randint(0, 1)
    if is_noise:
        img = add_gasuss_noise(img, mean=0, var=0.1)

    is_crop = random.randint(0, 1)
    if is_crop:
        img = get_crop(img)

    prob = 0.4
    img_height, img_width = img.shape[0:2]
    if img_height != 32:
        img = resize_norm_img(img)
    is_distort = random.randint(0, 1)
    if is_distort and img_height >= 20 and img_width >= 20:
        img = tia_distort(img, random.randint(3, 6))

    is_stretch = random.randint(0, 1)
    if is_stretch and img_height >= 20 and img_width >= 20:
        img = tia_stretch(img, random.randint(3, 6))
    
    is_perspective = random.randint(0, 1)
    if is_perspective and img_height >= 20 and img_width >= 20:
        img = tia_perspective(img)

    # Write
    # out_path = os.path.join(save_path, '{}.png'.format(i))

    # out_txt.writelines(out_path + '\t' + gt + '\n')
    # imwrite
    # cv2.imwrite(out_path, img)
    # img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
    # img = Image.fromarray(img)
    return img

txt_path = '/data2/lhw/Real_invoice_datasets/Croped_Checked/labels.txt'
txt_list = [line for line in open_txt(txt_path)]
random.shuffle(txt_list)
print('txt_list load Finshed')
count = 0
save_path = '/data2/lhw/Real_invoice_datasets/Croped_Checked_AUG'
out_txt = open(os.path.join(save_path, 'labels.txt'), 'w')
#
# pool = multiprocessing.Pool(processes=40)
# out = []
# for i in range(len(txt_list)):
#     if i < 160000:
#         pool.apply_async(img_aug, (i,))
#     else:
#         break
# pool.close()
# pool.join()
# print(out)
# count = 0
# for c in out:
#     gt = c.get().strip()
#     # Write
#     out_txt.writelines(gt)

for line in txt_list:
    img_path = line.split('\t')[0]
    gt = line.split('\t')[1].strip()
    img = cv2.imread(img_path)
    for c in range(10):
        out = img_aug(img)
        out_path = os.path.join(save_path, '{}_{}.png'.format(c, count))
        out_txt.writelines(out_path + '\t' + gt + '\n')
        cv2.imwrite(out_path, out)
        count += 1
print(count)

# image_shape = (3, 32, 320)
# img = cv2.imread('/data1/lhw/workspace/TextRecognitionDataGenerator/trdg/output/invoice_train_companies/5000007.jpg')
# print(img.shape)
# img_height, img_width = img.shape[0:2]
# # if random.random() <= prob and img_height >= 20 and img_width >= 20:
# #     try:
# #         img = tia_distort(img, random.randint(3, 6))
# #         # img = tia_stretch(img, random.randint(4, 20))
# #         # img = tia_perspective(img)
# #     except:
# #         pass
# #         print('error')
# out = get_crop(img)

# # out = img_aug(img)
# print(out.shape)

# out = resize_norm_img(out)
# print(out.shape)
# cv2.imwrite('tmp.png', out)